package com.mammoth.Bodybuilding.cors;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 
 * 
 * @title : CorsConfig.java
 * @description : cors 配置的
 * @company : com.mammoth.Bodybuilding.cors
 * @project Mammoth
 * @author xingzhaojun
 * @date 2018年4月26日上午11:38:50
 */
@Configuration
public class CorsConfig {
	@SuppressWarnings("rawtypes")
	@Bean
	public FilterRegistrationBean corsFilter() {
		/**
		 * crossDomain:true, xhrFields: { withCredentials: true },   ajax加上以上两个选项即可获取session
		 */
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		/** 设置你要允许的网站域名，如果全允许则设为 **/
		config.addAllowedOrigin("*");
		/** 如果要限制 HEADER 或 METHOD 请自行更改 **/
		config.addAllowedHeader("*");
		config.addAllowedMethod("*");
		source.registerCorsConfiguration("/**", config);
		@SuppressWarnings("unchecked")
		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
		/** 这个顺序很重要哦，为避免麻烦请设置在最前 **/
		bean.setOrder(0);
		return bean;
	}
}
